﻿//页面大小的通用配置 Add By wwj 2012-03-31 【1】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Data.OracleClient;
using System.Xml;
using System.Net;
using DBUtility;
using EMR.TimeLimitQC;
using EMR.Heart.Common;

namespace EMR.Util
{
    public class RecordDal
    {

        #region  const model data fields
        const string col_flag = "flag";
        const string col_minstanceid = "indx";
        const string col_Index = "ID";

        const string col_mpatid = "NoOfInpat";
        const string col_mmodelid = "TEMPLATEID";
        const string col_fileName = "FileNAME";
        const string col_mName = "Name";
        const string col_mdescription = "RecordDesc";
        const string col_mcontent = "filecontent";
        const string col_content = "Content";
        const string col_mcatalog = "SortID";
        const string col_mjlzt = "Valid";
        const string col_mcjys = "Owner";
        const string col_mcjsj = "CreateTime";
        const string col_mtjzt = "HasSubmit";
        const string col_mdyzt = "HasPrint";
        const string col_mshys = "Auditor";
        const string col_mshsj = "AuditTime";
        const string col_dzqmbz = "HasSign";
        const string col_cdt = "CaptionDateTime";
        const string col_fdf = "FIRSTDAILYFLAG";
        const string col_IsShowFileName = "isshowfilename";
        const string s_ModelTableName = "RecordDetail";
        const string col_py = "PY";
        const string col_wb = "WB";
        const string col_yihuangoutong = "isyihuangoutong";
        const string col_IsReadConfigPageSize = "isconfigpagesize";//【1】


        string Sql_LoadModelInstance = String.Format(CultureInfo.CurrentCulture
          , @"select {0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {14}, {15}, {16}, {17}, {18} 
              from {13} where {0} = @{0} order by {5},{15}"
          , new string[] { col_Index, col_mpatid, col_mmodelid, col_mName, col_content // 0~4
            , col_mcatalog, col_mjlzt, col_mtjzt, col_mdyzt, col_mcjys, col_mcjsj, col_mshys, col_mshsj // 5~12
            , s_ModelTableName, col_dzqmbz, col_cdt, col_fdf, col_yihuangoutong   // 13~17
            , col_IsReadConfigPageSize/*【1】*/});  // 18


        string Sql_UpdateModelInstance = String.Format(CultureInfo.CurrentCulture
         , " update {0}"
         + " set {3} = @{3}, {4} = @{4}, {5} = @{5}, {6} = @{6}, {7} = @{7}, {8} = @{8}, {9} = @{9}, {10} = @{10}, {11} = @{11}, {12} = @{12}"
         + ", {13} = @{13}"
         + " where {1} = @{1} and {2} = @{2}"
         , new string[] { s_ModelTableName, col_mpatid, col_minstanceid, col_mmodelid, col_fileName // 0~4
            , col_mdescription, col_mcontent, col_mcatalog, col_mjlzt, col_mtjzt, col_mdyzt , col_mshys, col_mshsj, col_dzqmbz}); // 5~14

        string Sql_UpdateModelPrintSigned = String.Format(CultureInfo.CurrentCulture
         , " update {0} set {1} = @{1} where {2} = @{2} "
         , new string[] { s_ModelTableName, col_mdyzt, col_minstanceid });

        /// <summary>
        /// 作废病历
        /// </summary>
        string Sql_UpdateModelValid = String.Format(CultureInfo.CurrentCulture
         , " update {0} set {1} = '0' where {2} = @{2} "
         , new string[] { s_ModelTableName, col_mjlzt, col_Index });

        string Sql_GetMaxFileNo = string.Format("select max(ID) from {0}", s_ModelTableName);
        string Sql_GetQCCode = "select QC_CODE from emrtemplet where TEMPLET_ID='{0}' ";

        #endregion
        IDataAccess sql_Helper;
        Qcsv QC_Sqlhelper;
        public RecordDal(IDataAccess sqlhelper)
        {
            sql_Helper = sqlhelper;

        }


        /// <summary>
        /// 病历文件SQL语句的参数
        /// </summary>
        private SqlParameter[] ModelInstanceParams
        {
            get
            {
                if (_modelInstanceParams == null)
                    _modelInstanceParams = GetEmrModelInstanceParameters();
                return _modelInstanceParams;
            }
        }
        private SqlParameter[] _modelInstanceParams;

        /// <summary>
        /// 设置参数, 注意Text类型用sqldbtype.ntext,不要用sqldbtype.text
        /// </summary>
        /// <returns></returns>
        /// <summary>
        /// 设置参数, 注意Text类型用sqldbtype.ntext,不要用sqldbtype.text
        /// </summary>
        /// <returns></returns>
        private SqlParameter[] GetEmrModelInstanceParameters()
        {
            SqlParameter[] parms = new SqlParameter[] {
            new SqlParameter(col_flag,SqlDbType.Int,10),    
            new SqlParameter(col_minstanceid,SqlDbType.Int,10),
            new SqlParameter(col_mpatid, SqlDbType.Int, 32),
            new SqlParameter(col_mmodelid, SqlDbType.VarChar, 64),
            new SqlParameter(col_fileName,SqlDbType.VarChar,64),
            //new SqlParameter(col_mdescription,SqlDbType.VarChar, 255),
            new SqlParameter(col_mcontent,SqlDbType.VarChar, int.MaxValue),
            new SqlParameter(col_mcatalog, SqlDbType.VarChar,12),
            new SqlParameter(col_mcjys, SqlDbType.VarChar,6),
            new SqlParameter(col_mcjsj, SqlDbType.VarChar,19)
            ,new SqlParameter(col_mshys, SqlDbType.VarChar, 6)
            ,new SqlParameter(col_mshsj, SqlDbType.VarChar, 19)
            ,new SqlParameter(col_dzqmbz, SqlDbType.SmallInt,10)
            ,new SqlParameter(col_mjlzt, SqlDbType.SmallInt)
            ,new SqlParameter(col_mtjzt, SqlDbType.SmallInt)
            ,new SqlParameter(col_mdyzt, SqlDbType.SmallInt)
            ,new SqlParameter(col_cdt, SqlDbType.VarChar, 19)//设置的病程时间CaptionDateTime
            ,new SqlParameter(col_fdf, SqlDbType.VarChar, 1)//首次病程标志位
            ,new SqlParameter(col_py, SqlDbType.VarChar, 20)//拼音
            ,new SqlParameter(col_wb, SqlDbType.VarChar, 20)//五笔
            ,new SqlParameter(col_yihuangoutong, SqlDbType.VarChar, 1)
            ,new SqlParameter(col_IsReadConfigPageSize, SqlDbType.VarChar, 1)//【1】
         };
            return parms;
        }


        public static string ZipEmrXml(string emrContent)
        {
            byte[] buffUnzipXml = Encoding.UTF8.GetBytes(emrContent);
            MemoryStream ms = new MemoryStream();
            GZipStream dfs = new GZipStream(ms, CompressionMode.Compress, true);
            dfs.Write(buffUnzipXml, 0, buffUnzipXml.Length);
            dfs.Close();
            ms.Seek(0, SeekOrigin.Begin);
            byte[] buffZipXml = new byte[ms.Length];
            ms.Read(buffZipXml, 0, buffZipXml.Length);
            return Convert.ToBase64String(buffZipXml);
        }

        public static string UnzipEmrXml(string emrContent)
        {
            try
            {
                byte[] rbuff = Convert.FromBase64String(emrContent);
                MemoryStream ms = new MemoryStream(rbuff);
                GZipStream dfs = new GZipStream(ms, CompressionMode.Decompress, true);
                StreamReader sr = new StreamReader(dfs, Encoding.UTF8);
                string sXml = sr.ReadToEnd();
                sr.Close();
                dfs.Close();
                return sXml;
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e);
                return emrContent;
            }
        }

        //作废
        //private void UpdateEmrContent(string emrContent, string indx)
        //{
        //    if (emrContent == "") return;
        //    OracleLob lob;
        //    OracleTransaction txn = null;
        //    OracleConnection conn = null;
        //    OracleCommand cmd = null;
        //    OracleDataReader dr = null;
        //    string strSql = string.Empty;
        //    string content = string.Empty;
        //    Exception exception = null;
        //    try
        //    {
        //        conn = new OracleConnection(sql_Helper.GetDbConnection().ConnectionString);
        //        conn.Open();
        //        txn = conn.BeginTransaction();
        //        cmd = new OracleCommand(strSql, conn, txn);

        //        try
        //        {
        //            //用于在服务器上保存病历的副本 Add By wwj 2012-01-10
        //            SaveEmrFile(emrContent, indx);

        //            //保存修改主机的IP Add By wwj 2012-01-10
        //            IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
        //            if (IpEntry.AddressList.Length > 0)
        //            {
        //                IPAddress ipAddr = IpEntry.AddressList[0];
        //                sql_Helper.ExecuteNoneQuery("update recorddetail set ip ='" + ipAddr.ToString() + "' where id=" + indx);
        //            }
        //        }
        //        catch (Exception ex)
        //        { }

        //        cmd.CommandText = "SELECT content FROM recorddetail where ID=" + indx + " FOR UPDATE";
        //        dr = cmd.ExecuteReader();
        //        while (dr.Read())
        //        {
        //            lob = dr.GetOracleLob(0);
        //            lob.Erase();
        //            if (lob != OracleLob.Null)
        //            {
        //                //content = lob.Value.ToString();
        //                content = emrContent;
        //                byte[] buffer = System.Text.Encoding.Unicode.GetBytes(content);
        //                lob.Write(buffer, 0, buffer.Length);
        //            }
        //        }
        //        txn.Commit();
        //    }
        //    catch (Exception ex)
        //    {
        //        txn.Rollback();
        //        exception = ex;
        //    }
        //    finally
        //    {
        //        dr.Close();
        //        conn.Close();
        //        cmd.Dispose();
        //    }

        //    if (exception != null)
        //    {
        //        throw exception;
        //    }
        //}

        delegate void SaveEmrFileDelegate(string emrContent, string indx);
        private void SaveEmrFileMethod(string emrContent, string indx)
        {
            try
            {
                //【1.1】在服务器上保存病历的副本
                SaveEmrFile(emrContent, indx);

                //【1.2】保存修改主机的IP
                IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
                if (IpEntry.AddressList.Length > 0)
                {
                    IPAddress ipAddr = IpEntry.AddressList[0];
                    sql_Helper.ExecuteNoneQuery("update recorddetail set ip ='" + ipAddr.ToString() + "' where id=" + indx);
                }
            }
            catch (Exception ex)
            { }
        }

        private void UpdateEmrContent(string emrContent, string indx)
        {
            //【1】以文件的形式保存病历副本
            (new SaveEmrFileDelegate(SaveEmrFileMethod)).BeginInvoke(emrContent, indx, null, null);

            //【2】将病历数据保存到数据库中
            OracleConnection conn = new OracleConnection(sql_Helper.GetDbConnection().ConnectionString);
            OracleCommand cmd = conn.CreateCommand();
            try
            {
                conn.Open();
                cmd.CommandText = "update recorddetail set content = :data where id =" + indx;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Clear();
                OracleParameter paraClob = new OracleParameter("data", OracleType.Clob);
                paraClob.Value = emrContent;
                cmd.Parameters.Add(paraClob);
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }

        private void SetEmrModelInstanceParametersValue(EmrModel model, SqlParameter[] parms, int update, int patid)
        {
            if (model == null) throw new ArgumentNullException("model");
            if (parms == null) throw new ArgumentNullException("parms");
            parms[0].Value = update;
            parms[1].Value = model.InstanceId;
            parms[2].Value = patid;
            parms[3].Value = model.TempIdentity;
            parms[4].Value = model.ModelName;
            //parms[4].Value = model.Description;
            if (model.ModelContent != null)
            {
                //if (update == 2)
                //{
                //    parms[5].Value = DBNull.Value;
                //}
                //else
                //{
                //    parms[5].Value = ZipEmrXml(model.ModelContent.OuterXml);
                //}
                parms[5].Value = " ";
            }
            parms[6].Value = model.ModelCatalog;

            parms[7].Value = model.CreatorXH;
            parms[8].Value = model.CreateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
            {
                if (String.IsNullOrEmpty(model.ExaminerXH))
                    parms[9].Value = "";
                else
                    parms[9].Value = model.ExaminerXH;
                if (model.ExamineTime > DateTime.MinValue)
                    parms[10].Value = model.ExamineTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture);
                else
                    parms[10].Value = "";
            }
            parms[11].Value = model.HadSigned ? 1 : 0;
            parms[12].Value = model.Valid ? 1 : 0; // 有效记录
            //parms[13].Value = (int)model.State;
            parms[13].Value = 1;
            parms[14].Value = model.IsModifiedAfterPrint ? (int)PrintState.ChangedAfterPrint : (model.IsAfterPrint ? (int)PrintState.HadPrinted : (int)PrintState.IsNotPrinted);
            //if (model.State != ExamineState.NotSubmit) 审核属性有值就保存
            parms[15].Value = model.DisplayTime == null ? "" : model.DisplayTime.ToString("yyyy-MM-dd HH:mm:ss");
            parms[16].Value = model.FirstDailyEmrModel == true ? "1" : "0";

            //得到拼音和五筆的编码
            //GenerateShortCode shortCode = new GenerateShortCode(sql_Helper);
            //string[] code = shortCode.GenerateStringShortCode(model.ModelName);
            string[] code = {"0","0"};
            parms[17].Value = code[0]; //PY
            parms[18].Value = code[1]; //WB

            parms[19].Value = model.IsYiHuanGouTong;
            parms[20].Value = model.IsReadConfigPageSize ? "1" : "0";//【1】
        }

        public int InsertModelInstance(EmrModel model, int patid)
        {
            if (model == null) throw new ArgumentNullException("model");
            int identity = -1;

            try
            {
                ////读取最大记录
                //using (IDataReader reader = sql_Helper.ExecuteReader(Sql_GetMaxFileNo))
                //{
                //    reader.Read();
                //    if (reader.IsDBNull(0))
                //        identity = 0;
                //    else
                //        identity = reader.GetInt32(0) + 1;
                //    model.InstanceId = identity;
                //}
                model.CreateTime = DateTime.Now;

                //给参数赋值
                //model.ModelContent.PreserveWhitespace = true;
                SetEmrModelInstanceParametersValue(model, ModelInstanceParams, 1, patid);
                //插入sql
                DataTable dt = sql_Helper.ExecuteDataTable("usp_emr_patrecfile", ModelInstanceParams, CommandType.StoredProcedure);
                identity = Convert.ToInt32(dt.Rows[0][0]);

                //返回id；
                if (identity >= 0)
                {
                    model.InstanceId = identity;
                    if (model.ModelContent != null && model.ModelContent.OuterXml != "")
                    {
                        //modified by wwj
                        //UpdateEmrContent(ZipEmrXml(model.ModelContent.OuterXml), model.InstanceId.ToString());
                        UpdateEmrContent(model.ModelContent.OuterXml, model.InstanceId.ToString());
                    }
                    model.IsModified = false;
                }
                //保存时限
                UpdateQCRules(model, patid);
            }
            catch (Exception ex)
            {
                model.InstanceId = -1;
                System.Diagnostics.Trace.WriteLine("新增数据有误");
                System.Diagnostics.Trace.WriteLine(ex);
                throw ex;
            }
            return identity;
        }

        public void UpdateModelInstance(EmrModel model, int patid)
        {
            if (model == null) throw new ArgumentNullException("model");

            SetEmrModelInstanceParametersValue(model, ModelInstanceParams, 2, patid);
            sql_Helper.ExecuteDataTable("usp_emr_patrecfile", ModelInstanceParams, CommandType.StoredProcedure);

            if (model.ModelContent != null && model.ModelContent.OuterXml.Trim() != "")
            {
                //modified by wwj
                //UpdateEmrContent(ZipEmrXml(model.ModelContent.OuterXml), model.InstanceId.ToString());
                UpdateEmrContent(model.ModelContent.OuterXml, model.InstanceId.ToString());
            }

            model.IsModified = false;
        }

        public EmrModel LoadModelInstance(int instanceid)
        {
            SqlParameter[] parmas = new SqlParameter[]{
                new SqlParameter(col_Index, SqlDbType.Int, 32),
            };
            parmas[0].Value = instanceid;
            using (IDataReader record = sql_Helper.ExecuteReader(Sql_LoadModelInstance, parmas))
            {
                if (!record.Read()) return null;

                try
                {
                    EmrModel model = new EmrModel();
                    model.InstanceId = instanceid;
                    model.TempIdentity = record.GetString(2);
                    model.ModelName = record.GetString(3);
                    model.Description = model.ModelName;
                    model.ModelContent = new System.Xml.XmlDocument();
                    model.ModelContent.PreserveWhitespace = true;
                    string emrDoc = string.Empty;
                    if (!record.IsDBNull(4))
                    {
                        //modified by wwj
                        //emrDoc = UnzipEmrXml(record.GetString(4));
                        emrDoc = record.GetString(4);
                        if (emrDoc.Trim() != "")
                        {
                            model.ModelContent.LoadXml(emrDoc);
                        }
                    }

                    model.ModelCatalog = record.GetString(5);



                    // jlzt (记录状态,1 有效)
                    model.Valid = (record.GetInt16(6) == 1);

                    // tjzt (提交状态)
                    //model.State = (ExamineState)record.GetInt16(7);
                    // dyzt(打印状态)
                    if (record.GetInt16(8) == (int)PrintState.HadPrinted) //(cstDylbbh + 1))
                        model.IsAfterPrint = true;
                    else
                        if (record.GetInt16(8) == (int)PrintState.ChangedAfterPrint) //(cstDylbbh + 2))
                        {
                            model.IsAfterPrint = true;
                            model.IsModifiedAfterPrint = true;
                        }
                        else
                            model.IsAfterPrint = false;

                    if (record.GetString(9) != null)
                        model.CreatorXH = record.GetString(9);   //返回创建者

                    string strTime = record.GetString(10).Trim();
                    if (!string.IsNullOrEmpty(strTime))
                        model.CreateTime = DateTime.Parse(strTime, CultureInfo.CurrentCulture);
                    else
                        model.CreateTime = DateTime.MinValue;
                    if (!record.IsDBNull(11) && !string.IsNullOrEmpty(record.GetString(11).Trim()))
                        model.ExaminerXH = record.GetString(11);
                    if (!record.IsDBNull(12) && !string.IsNullOrEmpty(record.GetString(12).Trim()))
                        model.ExamineTime = DateTime.Parse(record.GetString(12));
                    model.HadSigned = (!record.IsDBNull(13) && (record.GetInt16(13) == 1));


                    if (!record.IsDBNull(14))
                    {
                        model.DisplayTime = Convert.ToDateTime(record.GetString(14).ToString());
                    }
                    if (!record.IsDBNull(15))
                    {
                        model.FirstDailyEmrModel = record.GetString(15) == "1" ? true : false;
                    }
                    //model.IsShowFileName = record.GetString(16);
                    //model.FileName = record.GetString(17);
                    if (!record.IsDBNull(16))
                    {
                        model.IsYiHuanGouTong = record.GetString(16);
                    }
                    if (!record.IsDBNull(17))//【1】
                    {
                        model.IsReadConfigPageSize = record.GetString(17) == "1" ? true : false;
                    }
                    return model;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.WriteLine("model数据有误");
                    System.Diagnostics.Trace.WriteLine(e);
                    return null;
                }
            }
        }

        public EmrModel LoadModelInstance(EmrModel model)
        {
            SqlParameter[] parmas = new SqlParameter[]{
                new SqlParameter(col_Index, SqlDbType.Int, 32),
            };
            parmas[0].Value = model.InstanceId;
            using (IDataReader record = sql_Helper.ExecuteReader(Sql_LoadModelInstance, parmas))
            {
                if (!record.Read()) return null;

                try
                {
                    model.TempIdentity = record.GetString(2);
                    model.ModelName = record.GetString(3);
                    model.Description = model.ModelName;
                    model.ModelContent = new System.Xml.XmlDocument();
                    model.ModelContent.PreserveWhitespace = true;
                    string emrDoc = string.Empty;
                    if (!record.IsDBNull(4))
                    {
                        //modified by wwj
                        //emrDoc = UnzipEmrXml(record.GetString(4));
                        emrDoc = record.GetString(4);
                        model.ModelContent.LoadXml(emrDoc);
                    }

                    model.ModelCatalog = record.GetString(5);

                    // jlzt (记录状态,1 有效)
                    model.Valid = (record.GetInt16(6) == 1);

                    // tjzt (提交状态)
                    //model.State = (ExamineState)record.GetInt16(7);
                    //model.State = 1;
                    // dyzt(打印状态)
                    if (record.GetInt16(8) == (int)PrintState.HadPrinted) //(cstDylbbh + 1))
                        model.IsAfterPrint = true;
                    else
                        if (record.GetInt16(8) == (int)PrintState.ChangedAfterPrint) //(cstDylbbh + 2))
                        {
                            model.IsAfterPrint = true;
                            model.IsModifiedAfterPrint = true;
                        }
                        else
                            model.IsAfterPrint = false;

                    if (record.GetString(9) != null)
                        model.CreatorXH = record.GetString(9);   //返回创建者

                    string strTime = record.GetString(10).Trim();
                    if (!string.IsNullOrEmpty(strTime))
                        model.CreateTime = DateTime.Parse(strTime, CultureInfo.CurrentCulture);
                    else
                        model.CreateTime = DateTime.MinValue;
                    if (!record.IsDBNull(11) && !string.IsNullOrEmpty(record.GetString(11).Trim()))
                        model.ExaminerXH = record.GetString(11);
                    if (!record.IsDBNull(12) && !string.IsNullOrEmpty(record.GetString(12).Trim()))
                        model.ExamineTime = DateTime.Parse(record.GetString(12));
                    model.HadSigned = (!record.IsDBNull(13) && (record.GetInt16(13) == 1));

                    if (!record.IsDBNull(14))
                    {
                        model.DisplayTime = Convert.ToDateTime(record.GetString(14));
                    }
                    if (!record.IsDBNull(15))
                    {
                        model.FirstDailyEmrModel = record.GetString(15) == "1" ? true : false;
                    }

                    //model.IsShowFileName = record.GetString(16);
                    //model.FileName = record.GetString(17);
                    if (!record.IsDBNull(16))
                    {
                        model.IsYiHuanGouTong = record.GetString(16);
                    }

                    if (!record.IsDBNull(17))//【1】
                    {
                        model.IsReadConfigPageSize = record.GetString(17) == "1" ? true : false;
                    }
                    return model;
                }
                catch (Exception e)
                {
                    System.Diagnostics.Trace.WriteLine("model数据有误");
                    System.Diagnostics.Trace.WriteLine(e);
                    return null;
                }
            }
        }

        /// <summary>
        /// 作废病历
        /// </summary>
        /// <param name="instanceid"></param>
        public void CancelEmrModel(int instanceid)
        {
            SqlParameter[] parmas = new SqlParameter[]{
                new SqlParameter(col_Index, SqlDbType.Int, 32),
            };
            parmas[0].Value = instanceid;
            sql_Helper.ExecuteReader(Sql_UpdateModelValid, parmas, CommandType.Text);
        }

        private void UpdateQCRules(EmrModel model, int patid)
        {
            if (QC_Sqlhelper == null)
                QC_Sqlhelper = new Qcsv();
            //获取监控结果
            string qcCode = QueryQCCode(model.TempIdentity);
            if (string.IsNullOrEmpty(qcCode)) return;


            QCResult qcResult = QC_Sqlhelper.SelectQCReslut(qcCode);
            //更新病历时限相关记录
            QC_Sqlhelper.UpdateRuleRecord(patid, model.InstanceId, model.CreatorXH, QCResultType.TimeChange, qcResult, DateTime.Now);

        }

        /// <summary>
        /// 获取当前病历的监控代码
        /// TODO:周辉
        /// 应该将病历的模板的监控代码合并到模型中
        /// 并扩展recodedetail库，增加qccode字段
        /// </summary>
        /// <param name="templeteid"></param>
        /// <returns></returns>
        private string QueryQCCode(string templeteid)
        {
            using (IDataReader reader = sql_Helper.ExecuteReader(string.Format(Sql_GetQCCode, templeteid)))
            {
                reader.Read();
                return reader.IsDBNull(0) ? string.Empty : reader.GetValue(0).ToString();
            }

        }


        /// <summary>
        /// 另存个人模板
        /// </summary>
        /// <param name="model"></param>
        /// <param name="userID"></param>
        /// <param name="memo"></param>
        public bool InsertTemplatePerson(EmrModel model, string userID, string memo, string content, string type, string deptid)
        {
            bool isOK = true;
            SqlParameter[] para = new SqlParameter[11];
            para[0] = new SqlParameter("@TEMPLATEID", SqlDbType.VarChar);
            para[0].Value = model.TempIdentity;
            para[1] = new SqlParameter("@NAME", SqlDbType.VarChar);
            para[1].Value = model.ModelName.Trim().Split(' ')[0];
            para[2] = new SqlParameter("@USERID", SqlDbType.VarChar);
            para[2].Value = userID;
            para[3] = new SqlParameter("@CONTENT", SqlDbType.VarChar, int.MaxValue);
            if (model.ModelContent != null)
            {
                //para[3].Value = ZipEmrXml(content);
            }
            para[4] = new SqlParameter("@SORTID", SqlDbType.VarChar);
            para[4].Value = model.ModelCatalog;
            para[5] = new SqlParameter("@MEMO", SqlDbType.VarChar);
            para[5].Value = memo;

            string[] code = GetPYWB(model.ModelName.Trim().Split(' ')[0]);
            para[6] = new SqlParameter("@PY", SqlDbType.VarChar);
            para[6].Value = code[0];
            para[7] = new SqlParameter("@WB", SqlDbType.VarChar);
            para[7].Value = code[1];
            para[8] = new SqlParameter("@TYPE", SqlDbType.VarChar);
            para[8].Value = type;
            //【1】
            para[9] = new SqlParameter("@ISCONFIGPAGESIZE", SqlDbType.VarChar);
            para[9].Value = model.IsReadConfigPageSize ? "1" : "0";

            para[10] = new SqlParameter("@DEPTID", SqlDbType.VarChar);
            para[10].Value = (type == "2") ? deptid : ""; //个人模板不记科室

            DataTable dt = sql_Helper.ExecuteDataTable("EMR_RECORD_INPUT.usp_InsertTemplatePerson", para, CommandType.StoredProcedure);
            int identity = -1;

            identity = Convert.ToInt32(dt.Rows[0][0]);
            //返回id；
            if (identity >= 0)
            {
                if (!string.IsNullOrEmpty(content))
                {
                    OracleConnection conn = new OracleConnection(sql_Helper.GetDbConnection().ConnectionString);
                    OracleCommand cmd = conn.CreateCommand();
                    try
                    {
                        conn.Open();
                        cmd.CommandText = "update template_person set content = :data where id =" + identity;
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.Clear();
                        OracleParameter paraClob = new OracleParameter("data", OracleType.Clob);
                        paraClob.Value = ZipEmrXml(content); ;
                        cmd.Parameters.Add(paraClob);
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        isOK = false;
                        throw ex;
                    }
                    finally
                    {
                        cmd.Dispose();
                        conn.Close();
                        conn.Dispose();
                    }
                }
            }
            return isOK;
        }

        /// <summary>
        /// 得到拼音和五笔
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string[] GetPYWB(string name)
        {
            //GenerateShortCode shortCode = new GenerateShortCode(sql_Helper);
            //string[] code = shortCode.GenerateStringShortCode(name);
            string[] code = { "", "" };
            //string py = code[0]; //PY
            //string wb = code[1]; //WB
            return code;
        }

        /// <summary>
        /// 通过类别码得到具体的类别名称
        /// </summary>
        /// <param name="catalog"></param>
        /// <returns></returns>
        public string GetCatalog(string catalog)
        {
            string sqlGetCatalog = " select cname from DICT_CATALOG where ccode = '" + catalog + "' ";
            return sql_Helper.ExecuteScalar(sqlGetCatalog, CommandType.Text).ToString();
        }

        //获得可替换项
        public DataTable GetReplaceItem(string modelName)
        {
            //string sqlGetReplaceImte = " select * from EMR_REPLACE_ITEM where instr('" + modelName + "',dest_emrname) = 1 " + " and valid = '1' ";

            string sqlGetReplaceImte = " select * from EMR_REPLACE_ITEM where valid = '1'"; 

            if (!string.IsNullOrEmpty(modelName))
            {
                sqlGetReplaceImte = sqlGetReplaceImte + " and ( instr('" + modelName + "',dest_emrname) = 1 or dest_emrname is null) ";
            }
            return sql_Helper.ExecuteDataTable(sqlGetReplaceImte, CommandType.Text);
        }

        //通过目标病历获得源病历
        public List<string> GetSourceEMRByDestEmrName(string destEmrModelName, DataTable dt)
        {
            List<string> replaceEmrList = new List<string>();
            if (dt != null)
            {
                var sourceEMR = (from DataRow dr in dt.Rows
                                 select dr["source_emrname"].ToString()).Distinct();
                foreach (var q in sourceEMR)
                {
                    replaceEmrList.Add(q.ToString());
                }
            }
            return replaceEmrList;
        }

        //通过目标项和目标病历获得源病历
        public List<string> GetSourceEMRByDestItemAndDestEmrName(string destEmrModelName, string destItem, DataTable dt)
        {
            List<string> list = new List<string>();
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["dest_itemname"].ToString() == destItem)
                    {
                        string source_emrname = dr["source_emrname"].ToString();
                        string source_itemname = dr["source_itemname"].ToString();
                        list.Add(source_emrname);
                        list.Add(source_itemname);
                        break;
                    }
                }
            }
            return list;
        }

        public List<EmrModelContainer> GetConsultRecrod(DataRow dr, string noofinpat)
        {
            string sqlConsultRecord = @"select '会诊记录' || ' ' || applytime || ' ' || (select name from users where users.id = applyuser) cname, consultapplysn 
                                        from consultapply where noofinpat={0} and stateid in('6730','6740','6741') ";
            DataTable dt = sql_Helper.ExecuteDataTable(string.Format(sqlConsultRecord, noofinpat), CommandType.Text);
            List<EmrModelContainer> list = new List<EmrModelContainer>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dr["CNAME"] = dt.Rows[i]["cname"].ToString();
                EmrModelContainer container = new EmrModelContainer(dr);
                container.Args = dt.Rows[i]["consultapplysn"].ToString();
                list.Add(container);
            }
            return list;
        }


        /// <summary>
        /// 用于在服务器上保存病历的副本  Add By wwj 2012-01-10
        /// </summary>
        /// <param name="content"></param>
        /// <param name="indx"></param>
        private void SaveEmrFile(string content, string indx)
        {
            DataTable dt = sql_Helper.ExecuteDataTable(
                @"SELECT i.noofinpat || '_' || i.name inpatient_name, r.name emr_name 
                    FROM recorddetail r, inpatient i 
                   WHERE r.noofinpat = i.noofinpat AND r.valid = '1' AND r.id =" + indx);
            if (dt.Rows.Count > 0)
            {
                string inpatientName = dt.Rows[0]["inpatient_name"].ToString();
                string emrName = dt.Rows[0]["emr_name"].ToString();

                string config = sql_Helper.ExecuteScalar("SELECT value FROM appcfg WHERE appcfg.configkey = 'EmrContentCopy' AND appcfg.valid = '1'").ToString();
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(config);

                string sourcefoldername = doc.GetElementsByTagName("sourcefoldername")[0].InnerText.Trim();
                string destfoldername = doc.GetElementsByTagName("destfoldername")[0].InnerText.Trim();
                string username = doc.GetElementsByTagName("username")[0].InnerText.Trim();
                string password = doc.GetElementsByTagName("password")[0].InnerText.Trim();

                string folderName = sourcefoldername;
                string destFolderName = destfoldername;

                if (!Directory.Exists(folderName))
                {
                    Directory.CreateDirectory(folderName);
                }
                folderName += @"\" + inpatientName;
                if (!Directory.Exists(folderName))
                {
                    Directory.CreateDirectory(folderName);
                }
                string fileName = folderName + @"\" + "ID=" + indx + " " + emrName.Replace(':', '-') + ".txt";
                FileStream fs = File.Create(fileName);

                Byte[] info = new UTF8Encoding(true).GetBytes(content);
                fs.Write(info, 0, info.Length);
                fs.Close();

                CopyDirectory(sourcefoldername, destfoldername, username, password);
            }
        }

        #region 病历副本备份  Add By wwj 2012-01-10

        /// <summary>
        /// 拷贝文件夹到服务器
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        private void CopyDirectory(String source, String destination, string user, string pwd)
        {
            try
            {
                //System.Diagnostics.Process.Start("net.exe ", @"use   \\192.168.2.13\病历备份   /user:" + user + "   " + pwd + " ");

                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("net.exe ", @"use   " + destination + "   /user:" + user + "   " + pwd + " ");
                psi.RedirectStandardOutput = true;
                psi.CreateNoWindow = true;
                psi.UseShellExecute = false;
                System.Diagnostics.Process.Start(psi);

                if (Directory.Exists(source) && Directory.Exists(destination))
                {
                    CopyDirectoryInner(source, destination);

                    //拷贝完成后将原目录删除
                    Directory.Delete(source, true);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
            }
        }

        private void CopyDirectoryInner(String source, String destination)
        {
            DirectoryInfo info = new DirectoryInfo(source);
            FileSystemInfo[] sysInfos = info.GetFileSystemInfos();

            foreach (FileSystemInfo fsi in info.GetFileSystemInfos())
            {
                string destName = Path.Combine(destination, fsi.Name);
                string srcName = Path.Combine(source, fsi.Name);

                //if file ,then copy it
                if (fsi is System.IO.FileInfo)
                {
                    string sourceName = Path.Combine(source, fsi.Name);
                    //just in case the destination is readonly
                    if (File.Exists(destName))
                    {
                        new FileInfo(destName).IsReadOnly = false;
                    }

                    File.Copy(fsi.FullName, destName, true);
                }
                else if (fsi is System.IO.DirectoryInfo)
                {
                    if (!Directory.Exists(destName))
                    {
                        Directory.CreateDirectory(destName);
                    }
                    CopyDirectoryInner(srcName, destName);
                }
            }
        }
        #endregion

        /// <summary>
        /// 得到诊断事件
        /// </summary>
        /// <returns></returns>
        public DataTable GetDiagButtonEvent()
        {
            DataTable dt = sql_Helper.ExecuteDataTable(sqlGetDiag, CommandType.Text);
            return dt;
        }
        private string sqlGetDiag = "SELECT * FROM patdiagtype order by code";

        #region 历史病历相关

        /// <summary>
        /// 得到历史病人记录
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public DataTable GetHistoryInpatient(int noofinpat)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("NOOFINPAT", SqlDbType.VarChar)
            };
            sqlParams[0].Value = noofinpat;
            return sql_Helper.ExecuteDataTable("emr_record_input.usp_getHistoryInpatient", sqlParams, CommandType.StoredProcedure);
        }

        /// <summary>
        /// 得到历史病人文件夹
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public DataTable GetHistoryInpatientFolder(int noofinpat)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("NOOFINPAT", SqlDbType.VarChar)
            };
            sqlParams[0].Value = noofinpat;
            return sql_Helper.ExecuteDataTable("emr_record_input.usp_getHistoryInpatientFolder", sqlParams, CommandType.StoredProcedure);
        }

        /// <summary>
        /// 得到病人入院次数
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public string GetHistoryInCount(int noofinpat)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("NOOFINPAT", SqlDbType.VarChar)
            };
            sqlParams[0].Value = noofinpat;
            DataTable dt = sql_Helper.ExecuteDataTable("emr_record_input.usp_getHistoryInCount", sqlParams, CommandType.StoredProcedure);
            return dt.Rows[0][0].ToString();
        }
        #endregion

        /// <summary>
        /// 得到病人入院次数
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public DataTable GetPatientInfo(int noofinpat)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("NOOFINPAT", SqlDbType.VarChar)
            };
            sqlParams[0].Value = noofinpat;
            return sql_Helper.ExecuteDataTable("emr_record_input.usp_getPatinetInfo", sqlParams, CommandType.StoredProcedure);
        }

        /// <summary>
        /// 得到病人历史病历
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public DataTable GetPatientHistoryEMR(int noofinpat, string sortid)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("NOOFINPAT", SqlDbType.VarChar),
                new SqlParameter("sortid", SqlDbType.VarChar)
            };
            sqlParams[0].Value = noofinpat;
            sqlParams[1].Value = sortid;
            return sql_Helper.ExecuteDataTable("emr_record_input.usp_getHistoryEMR", sqlParams, CommandType.StoredProcedure);
        }

        /// <summary>
        /// 得到具体的病历
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public string GetEmrContentByID(string recorddetailid)
        {
            SqlParameter[] sqlParams = new SqlParameter[]
            {
                new SqlParameter("recorddetailid", SqlDbType.VarChar)
            };
            sqlParams[0].Value = recorddetailid;
            DataTable dt = sql_Helper.ExecuteDataTable("emr_record_input.usp_EmrContentByID", sqlParams, CommandType.StoredProcedure);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["content"].ToString();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 得到病人病历的数据
        /// </summary>
        /// <param name="noofinpat"></param>
        /// <returns></returns>
        public int GetEmrCountByNoofinpat(string noofinpat)
        {
            //排除护理病历
            string sqlGetEmrCount = " select count(1) from recorddetail where noofinpat = '{0}' and valid = '1' and sortid not in('AI','AJ','AK') ";
            int inCount = Convert.ToInt32(sql_Helper.ExecuteDataTable(string.Format(sqlGetEmrCount, noofinpat), CommandType.Text).Rows[0][0]);
            return inCount;
        }

        public DataTable GetEmrRecordByNoofinpat(string noofinpat)
        {
            string sqlGetEmrRecordByNoofinpat = @"select id, name from recorddetail where noofinpat = '{0}' and valid = '1' order by sortid, captiondatetime";
            return sql_Helper.ExecuteDataTable(string.Format(sqlGetEmrRecordByNoofinpat, noofinpat));
        }


        /// <summary>
        /// 得到个人模板
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetTemplatePersonContent(string id)
        {
            string getTemplatePersonContent = " select template_person.content from template_person where template_person.id = '{0}' ";
            DataTable dt = this.sql_Helper.ExecuteDataTable(string.Format(getTemplatePersonContent, id), CommandType.Text);
            return dt.Rows[0][0].ToString();
        }
    }
}
